# coding=utf8

class Preliminary:

    @staticmethod
    def try_test1():
        """
        无论是否出现异常，是否有continue和break,甚至return，finally都会执行
        """
        try:
            a = "1" + 2
        except TypeError as e:
            print(e)
        else:
            print(a)
            return "else-return"
        finally:
            print("finally-return")
        return "end-return"

    @staticmethod
    def try_test2():
        """
        # 如果多个return可以执行，以最后一个生效
        # 内层try不能处理的异常，会传递到外层再处理
        # 如果finally子句中出现异常，需要再次捕获，否则会传递到外层处理
        # 外层不能处理的异常，会传递给系统处理
        """
        try:
            try:
                a = 1/0 + "2"
                return a
            except ZeroDivisionError as e:
                print(e)
            finally:
                return 100
        except (ValueError, TypeError, ZeroDivisionError) as e:
            print(e)
        finally:
            try:
                print("finally2")
                return a + 100
            except UnboundLocalError as e:
                print(e)
            finally:
                return 200

    @staticmethod
    def try_test3():
        """使用多个exception依次捕获异常"""
        try:
            a = '1' + 100
            b = 1/0
        except ValueError as e1:
            print("ValueError:", e1)
        except TypeError as e2:
            print("TypeError:", e2)
        except ZeroDivisionError as e3:
            print("Error3:", e3)
        else:
            return a
        finally:
            a = 200
        return a

    @staticmethod
    def try_test4():
        """
        没有exception语句
        输入值为0时退出
        """
        b = 0
        while True:
            try:
                a = input("input a number:")
                b = float(a)
                if b == 0:
                    break
            finally:
                print(b)
        return b

    @staticmethod
    def user_exception():

        class MyException(Exception):
            def __init__(self, value=0):
                self.value = value

            def __str__(self):
                return "Value({}) is too big!".format(self.value)

        x = 100
        if x > 50:
            raise MyException(x)


def task():
    t = 0
    while True:
        a = input('请输入第1个数字:')
        b = input('请输入第2个数字:')
        try:
            _a = float(a)
            _b = float(b)
            r = _a + _b
            print("求和结果：", r)
        except ValueError as e:
            print(e)
        else:
            break
        finally:
            t = t + 1
            print('当前输入次数为：', t)


if __name__ == '__main__':
    print(Preliminary.try_test1())
    # print(Preliminary.try_test2())
    # print(Preliminary.try_test3())
    # print(Preliminary.try_test4())

    # Preliminary.user_exception()
    # task()
